/**
 * Definition for singly-linked list.
 * class ListNode {
 *     val: number
 *     next: ListNode | null
 *     constructor(val?: number, next?: ListNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.next = (next===undefined ? null : next)
 *     }
 * }
 */

class ListNode {
    val: number
    next: ListNode | null
    constructor(val?: number, next?: ListNode | null) {
        this.val = (val === undefined ? 0 : val)
        this.next = (next === undefined ? null : next)
    }
}

/**
 * https://leetcode-cn.com/problems/add-two-numbers/
 * 
 * 两数相加
 * @param l1 
 * @param l2 
 */
const addTwoNumbers = (l1: ListNode | null, l2: ListNode | null): ListNode | null => {
    // 1. 判空
    if (l1 == null) return l2;
    if (l2 === null) return l1;

    // 2. 对两个链表进行遍历
    const dummyHead = new ListNode(0)

    let l: ListNode | null = l1,
        r: ListNode | null = l2;
    // 进位
    let carry = 0,
        // 当前节点
        curr = dummyHead;
    while (l !== null && r !== null) {
        let total = (l === null ? 0 : l.val) + (r === null ? 0 : r.val) + carry

        // 更新进位
        carry = total >= 10 ? 1 : 0

        // 创建新节点
        curr = curr.next = new ListNode(carry === 1 ? total - 10 : total);

        l = l && l.next;
        r = r && r.next;
    }



    // 最后的进位
    if (carry === 1) {
        curr.next = new ListNode(carry)
    }

    return dummyHead.next;
};

const addTwoNumbers2 = (l1: ListNode | null, l2: ListNode | null): ListNode | null => {
    // 1. 判空
    if (l1 == null) return l2;
    if (l2 === null) return l1;

    // 2. 对两个链表进行遍历
    const dummyHead = new ListNode(0)

    let l = l1,
        r = l2;
    // 进位
    let carry = 0,
        // 当前节点
        curr = dummyHead;
    while (l !== null && r !== null) {
        let total = l.val + r.val + carry
        // 创建新节点
        curr = curr.next = new ListNode(total % 10);

        // 更新进位
        carry = total >= 10 ? 1 : 0

        l = l.next!;
        r = r.next!;
    }

    // 左边还没完
    while (l !== null) {
        let total = l.val + carry;
        carry = total >= 10 ? 1 : 0
        curr = curr.next = new ListNode(total % 10)

        l = l.next!;
    }

    // 右边还没完
    while (r !== null) {
        let total = r.val + carry;
        carry = total >= 10 ? 1 : 0
        curr = curr.next = new ListNode(total % 10)

        r = r.next!;
    }

    // 最后的进位
    if (carry === 1) {
        curr.next = new ListNode(carry)
    }

    return dummyHead.next;
};


export {}